延續使用人類(Human)物件
#myclass.py
class Human:
def __init__(self,h=0,w=0):
self.height=h
self.weight=w
def BMI(self):
return self.weight / ((self.height/100)**2)
如果今天人類(Human)物件要進行運算的動作(+,-,*,/...)
例如
import myclass
a = mclass.Human(180,80)
b = mclass.Human(170,70)
a+b????
a+=b????
我們可以實作覆寫掉對應的特殊方法
__add__ +
__iadd__ +=
__sub__ -
__isub__ -=
__mul__ *
__imul__ *=
__truediv__ /
__itruediv__ /=
__floordiv__ //
__ifloordiv__ //=
__mod__ %
__imod__ %=
__pow__ **
__ipow__ **=
舉個例子
我們設定如果a人類(Human)物件與b人類(Human)物件相加(a+b),定義為傳回身高(height)相加
如果是a+=b, 定義為把a的身高(height)與體重(weight)相加後設定成a物件
#myclass.py
class Human:
def __init__(self,h=0,w=0):
self.height=h
self.weight=w
def BMI(self):
return self.weight / ((self.height/100)**2)
def __add__(self,other):
return self.height + other.height
def __iadd__(self,other):
self.height += other.height
self.weight += other.weight
return self
#main.py
import myclass
a = myclass.Human(180,80)
b = myclass.Human(170,70)
print(a+b)
print(a.height,a.weight)
a+=b
print(a.height,a.weight)